from pandac.PandaModules import QueuedConnectionManager
from pandac.PandaModules import PointerToConnection,NetAddress
from pandac.PandaModules import QueuedConnectionReader
from pandac.PandaModules import ConnectionWriter
from QNetwork import QNetwork

class QClient(QNetwork):
    timeout_in_miliseconds = 1000  # 3 seconds
    def Setup(self,
              ip_address='localhost',
              port_address=QNetwork.default_Port):
        self.cManager = QueuedConnectionManager()
        self.cReader = QueuedConnectionReader(self.cManager, 0)
        self.cWriter = ConnectionWriter(self.cManager,0)
        self.tcpSocket = self.cManager.openTCPClientConnection(ip_address,
                                                               port_address,
                                                               QClient.timeout_in_miliseconds)
        self.tcpSocket.setNoDelay(True)
        if self.tcpSocket:
            self.cReader.addConnection(self.tcpSocket)
            self.ConnectionTargetDictReset(1)  # link target = server
            i = self.ConnectionTargetAdd(self.tcpSocket)
            self.NewConnectionHandle(i)
            ret = True
        else:
            ret = False

        # add task
        if ret:
            self.ReaderPollingEnable()

        return ret
